package com.ruoyi.audit.service.impl;

import com.ruoyi.audit.domain.AmountDetailed;
import com.ruoyi.audit.domain.Audit;
import com.ruoyi.audit.domain.InventoryAmount;
import com.ruoyi.audit.mapper.AmountDetailedMapper;
import com.ruoyi.audit.mapper.AuditMapper;
import com.ruoyi.audit.mapper.InventoryAmountMapper;
import com.ruoyi.audit.service.AuditService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.WXShiroUtils;
import com.ruoyi.company.domain.Company;
import com.ruoyi.company.domain.CompanyInvoice;
import com.ruoyi.company.domain.CompanyOther;
import com.ruoyi.company.mapper.CompanyInvoiceMapper;
import com.ruoyi.company.mapper.CompanyMapper;
import com.ruoyi.company.mapper.CompanyOtherMapper;
import com.ruoyi.company.utils.Util;
import com.ruoyi.company.utils.pdf.HtmlToPdf;
import com.ruoyi.company.utils.pdf.ImgToPdf;
import com.ruoyi.enterStock.mapper.EnterstockMapper;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.mateCheck.domain.MateCheck;
import com.ruoyi.mateCheck.domain.MateCheckModel;
import com.ruoyi.mateCheck.domain.MateTest;
import com.ruoyi.mateCheck.domain.MateUserDevice;
import com.ruoyi.mateCheck.mapper.MateCheckMapper;
import com.ruoyi.mateDevice.mapper.MateDeviceMapper;
import com.ruoyi.mateProcurement.domain.MateOutbound;
import com.ruoyi.mateProcurement.domain.MateOutboundModel;
import com.ruoyi.mateProcurement.domain.MateProcurement;
import com.ruoyi.mateProcurement.domain.MateProcurementModel;
import com.ruoyi.mateProcurement.mapper.MateOutboundMapper;
import com.ruoyi.mateProcurement.mapper.MateProcurementMapper;
import com.ruoyi.mateWarehousing.domain.MateWarehousing;
import com.ruoyi.mateWarehousing.mapper.MateWarehousingMapper;
import com.ruoyi.material.domain.MateProductCheck;
import com.ruoyi.material.mapper.CheckReportMapper;
import com.ruoyi.monthlyInventory.domain.MonthlyInventoryLog;
import com.ruoyi.monthlyInventory.mapper.MonthlyInventoryMapper;
import com.ruoyi.procurement.domain.ProcurementModel;
import com.ruoyi.procurement.domain.ProcurementOrder;
import com.ruoyi.procurement.mapper.ProcurementOrderMapper;
import com.ruoyi.procurement.service.impl.ProcurementOrderServiceImpl;
import com.ruoyi.purchase.domain.PurchaseModel;
import com.ruoyi.purchase.domain.PurchaseOrder;
import com.ruoyi.purchase.mapper.PurchaseOrderMapper;
import com.ruoyi.purchaseReturn.domain.PurchaseReturnOrder;
import com.ruoyi.purchaseReturn.mapper.PurchaseReturnMapper;
import com.ruoyi.readyProcurement.domain.ReadyProcurement;
import com.ruoyi.readyProcurement.mapper.ReadyMapper;
import com.ruoyi.sale.domain.*;
import com.ruoyi.sale.mapper.SaleGoodsMapper;
import com.ruoyi.sale.mapper.SaleorderMapper;
import com.ruoyi.saleReturn.domain.SaleReturnOrder;
import com.ruoyi.saleReturn.mapper.SaleReturnMapper;
import com.ruoyi.salesInvoice.domain.SalesInvoiceModel;
import com.ruoyi.salesInvoice.domain.SalesInvoiceOrder;
import com.ruoyi.salesInvoice.mapper.SalesInvoiceMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.warehousing.domain.Warehousing;
import com.ruoyi.warehousing.domain.WarehousingRecords;
import com.ruoyi.warehousing.mapper.WarehousingMapper;
import com.ruoyi.warehousing.mapper.WarehousingRecordsMapper;
import com.ruoyi.warehousing.service.impl.WarehousingServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 订单审核Service业务层处理
 *
 * @author zjh
 * @date 2022-04-25
 */
@Service
public class AuditServiceImpl implements AuditService {
    @Autowired
    MateCheckMapper mateCheckMapper;
    @Autowired
    private AuditMapper auditMapper;
    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;
    @Autowired
    private SaleorderMapper saleorderMapper;
    @Autowired
    private ProcurementOrderMapper procurementOrderMapper;
    @Autowired
    private SaleGoodsMapper saleGoodsMapper;
    @Autowired
    private MonthlyInventoryMapper monthlyInventoryMapper;
    @Autowired
    private PurchaseReturnMapper purchaseReturnMapper;
    @Autowired
    private SaleReturnMapper saleReturnMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private CompanyInvoiceMapper companyInvoiceMapper;
    @Autowired
    private CompanyOtherMapper companyOtherMapper;
    @Autowired
    private SalesInvoiceMapper salesInvoiceMapper;
    @Autowired
    private WarehousingServiceImpl warehousingService;
    @Autowired
    private ProcurementOrderServiceImpl procurementOrderServiceImpl;
    @Autowired
    private WarehousingMapper warehousingMapper;
    @Autowired
    private WarehousingRecordsMapper warehousingRecordsMapper;
    @Autowired
    private EnterstockMapper enterstockMapper;
    @Autowired
    private AmountDetailedMapper amountDetailedMapper;
    @Autowired
    private InventoryAmountMapper inventoryAmountMapper;
    @Autowired
    private MateProcurementMapper mateProcurementMapper;
    @Autowired
    private MateWarehousingMapper mateWarehousingMapper;
    @Autowired
    private MateOutboundMapper mateOutboundMapper;
    @Autowired
    private MateDeviceMapper mateDeviceMapper;

    @Autowired
    private CheckReportMapper checkReportMapper;

    @Autowired
    private ReadyMapper readyMapper;


    /**
     * 查询订单审核(入库)
     *
     * @param auditId 订单审核ID
     * @return 订单审核
     */
    @Override
    public Audit selectAuditByIdIn(Long auditId) {
        return auditMapper.selectAuditByIdIn(auditId);
    }

    /**
     * 查询订单审核
     *
     * @param auditId 订单审核ID
     * @return 订单审核
     */
    @Override
    public Audit selectAuditById(Long auditId) {
        return auditMapper.selectAuditById(auditId);
    }

    /**
     * 查询订单审核
     *
     * @param audit
     * @return 订单审核
     */
    @Override
    public Audit selectAuditByOrderId(Audit audit) {
        return auditMapper.selectAuditByOrderId(audit);
    }

    /**
     * 查询订单审核列表
     *
     * @param audit 订单审核
     * @return 订单审核
     */
    @Override
    public List<Audit> selectAuditList(Audit audit) {
        return auditMapper.selectAuditList(audit);
    }

    @Override
    public List<Audit> selectMateAuditList(Audit audit) {
        return auditMapper.selectMateAuditList(audit);
    }

    /**
     * 新增订单审核
     *
     * @param audit 订单审核
     * @return 结果
     */
    @Override
    public int insertAudit(Audit audit) {
        return auditMapper.insertAudit(audit);
    }

    /**
     * 修改订单审核
     *
     * @param audit 订单审核
     * @return 结果
     */
    @Override
    public int updateAudit(Audit audit, Long deptId) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Audit audit1 = auditMapper.selectAuditByIdIn(audit.getAuditId());
        if (audit.getAuditStatus() != null && !audit.getAuditStatus().equals("")) {
            audit1.setAuditStatus(audit.getAuditStatus());
        }
        if (audit.getAuditRemark() != null && !audit.getAuditRemark().equals("")) {
            audit1.setAuditRemark(audit.getAuditRemark());
        }
        audit1.setAuditBy(audit.getAuditBy());
        audit1.setAuditTime(audit.getAuditTime());
        int num = 0;
        if (audit1.getOrderType().equals("1")) {
            PurchaseOrder purchaseOrder = purchaseOrderMapper.selectPurchaseOrderById(audit1.getOrderId());
            purchaseOrder.setPurchaseStatus(audit.getAuditStatus());
            if (audit.getAuditStatus() != null && !audit.getAuditStatus().equals("")) {
                purchaseOrder.setAuditTime(DateUtils.getNowDate());
            }
            num = purchaseOrderMapper.updatePurchaseOrder(purchaseOrder);
            //将pdf上传到服务器 并且更新 pdfurl字段
            purchaseTopdf(audit1.getOrderId(), deptId);
        } else if (audit1.getOrderType().equals("0")) {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("saleorderId", audit1.getOrderId());
            hashMap.put("deptId", sysUser.getCompanyId());
            SaleorderOrder saleorderOrder = saleorderMapper.selectSaleorderById(hashMap);
            saleorderOrder.setSaleorderStatus(audit.getAuditStatus());
            if (audit.getAuditStatus() != null && !audit.getAuditStatus().equals("")) {
                saleorderOrder.setAuditTime(DateUtils.getNowDate());
            }

            num = saleorderMapper.updateSaleorder(saleorderOrder);
            if ("1".equals(audit.getAuditStatus()) && saleorderOrder.getPurchaseId() != null) {
                PurchaseOrder purchaseOrder = new PurchaseOrder();
                purchaseOrder.setPurchaseFlag("1");
                //purchaseOrder.setIsCreateSale(1);
                purchaseOrder.setPurchaseId(saleorderOrder.getPurchaseId());
                purchaseOrderMapper.updatePurchaseOrder(purchaseOrder);
            } else {
                //驳回销售订单
                for (int i = 0; i < saleorderOrder.getSaleorderModels().size(); i++) {
                    SaleorderModel model = saleorderOrder.getSaleorderModels().get(i);
                    PurchaseModel purchaseModel = new PurchaseModel();
                    purchaseModel.setModelId(model.getPurchaseModelId());
                    purchaseModel.setExecuteNum((long) model.getPurExecuteNum());
                    purchaseModel.setRemainingNum((long) model.getPurRemainingNum());
                    purchaseModel.setPurchaseNum(-1);
                    purchaseOrderMapper.updatePurchaseModel(purchaseModel);
                }
            }
            //将pdf上传到服务器 并且更新 pdfurl字段
            saleorderTopdf(audit1.getOrderId(), deptId);
        } else if (audit1.getOrderType().equals("2")) {
            ProcurementOrder procurementOrder = new ProcurementOrder();
            procurementOrder.setProcurementWarehousingId(audit1.getOrderId());
            procurementOrder.setAuditTime(DateUtils.getNowDate());
            procurementOrder.setProcurementStatus(audit.getAuditStatus());
            num = procurementOrderMapper.updateProcurementOrder(procurementOrder);
            Long orderId = audit1.getOrderId();
            ProcurementOrder procurementOrder1 = procurementOrderMapper.selectProcurementById(orderId);
            if (procurementOrder1 != null && procurementOrder1.getSaleGoodsId() != null && audit.getAuditStatus().equals("2")) {
                SaleGoodsOrder saleGoodsOrder = new SaleGoodsOrder();
                saleGoodsOrder.setSaleGoodsId(procurementOrder1.getSaleGoodsId());
                saleGoodsOrder.setIsWarehousingOrder(0);
                saleGoodsMapper.updateSaleGoodsOrder(saleGoodsOrder);
            }
        } else if ("3".equals(audit1.getOrderType())) {
            SaleGoodsOrder saleGoodsOrder = new SaleGoodsOrder();
            saleGoodsOrder.setSaleGoodsId(audit1.getOrderId());
            saleGoodsOrder.setAuditTime(DateUtils.getNowDate());
            saleGoodsOrder.setSaleGoodsStatus(audit.getAuditStatus());
            num = saleGoodsMapper.updateSaleGoodsOrder(saleGoodsOrder);
        } else if (audit1.getOrderType().equals("4")) {
            MonthlyInventoryLog monthlyInventoryLog = new MonthlyInventoryLog();
            monthlyInventoryLog.setLogId(audit1.getOrderId());
            monthlyInventoryLog.setAuditTime(DateUtils.getNowDate());
            monthlyInventoryLog.setAuditStatus(audit.getAuditStatus());
            num = monthlyInventoryMapper.updateMonthlyInventoryLog(monthlyInventoryLog);
        } else if (audit1.getOrderType().equals("5")) {
            PurchaseReturnOrder purchaseReturnOrder = new PurchaseReturnOrder();
            purchaseReturnOrder.setPurchaseReturnId(audit1.getOrderId());
            purchaseReturnOrder.setAuditTime(DateUtils.getNowDate());
            purchaseReturnOrder.setPurchaseReturnStatus(audit.getAuditStatus());
            num = purchaseReturnMapper.updatePurchaseReturn(purchaseReturnOrder);
        } else if ("6".equals(audit1.getOrderType())) {
            SaleReturnOrder saleReturnOrder = new SaleReturnOrder();
            saleReturnOrder.setSaleReturnId(audit1.getOrderId());
            saleReturnOrder.setAuditTime(DateUtils.getNowDate());
            saleReturnOrder.setSaleReturnStatus(audit.getAuditStatus());
            num = saleReturnMapper.updateSaleReturnOrder(saleReturnOrder);
        } else if ("7".equals(audit1.getOrderType())) {
            SalesInvoiceOrder salesInvoiceOrder = salesInvoiceMapper.selectSalesInvoiceOrderById(audit1.getOrderId());
            salesInvoiceOrder.setSalesInvoiceId(audit1.getOrderId());
            salesInvoiceOrder.setAuditTime(DateUtils.getNowDate());
            salesInvoiceOrder.setInvoiceStatus(audit.getAuditStatus());
            num = salesInvoiceMapper.updateSalesInvoiceOrder(salesInvoiceOrder);
        } else if ("8".equals(audit1.getOrderType())) {
            MateProcurement mateProcurement = mateProcurementMapper.selectMateProcurementByOrderId(audit1.getOrderId());
            if (audit.getAuditStatus().equals("1")) {
                ReadyProcurement readyProcurement = new ReadyProcurement();
                readyProcurement.setReadyId(mateProcurement.getReadyId());
                readyProcurement.setIsProcurement("1");
                readyMapper.updateReadyProcurement(readyProcurement);
            } else if (audit.getAuditStatus().equals("2")) {
                ReadyProcurement readyProcurement = new ReadyProcurement();
                readyProcurement.setReadyId(mateProcurement.getReadyId());
                readyProcurement.setIsProcurement("0");
                readyMapper.updateReadyProcurement(readyProcurement);
            }
            mateProcurement.setMateProcurementId(audit1.getOrderId());
            mateProcurement.setAuditTime(DateUtils.getNowDate());
            mateProcurement.setProcurementStatus(audit.getAuditStatus());
            num = mateProcurementMapper.updateProcurement(mateProcurement);
        } else if ("9".equals(audit1.getOrderType())) {
            MateOutbound mateOutbound = mateOutboundMapper.selectMateOutboundByOrderId(audit1.getOrderId());
            mateOutbound.setMateGoodsId(audit1.getOrderId());
            mateOutbound.setAuditTime(DateUtils.getNowDate());
            mateOutbound.setMateGoodsStatus(audit.getAuditStatus());
            num = mateOutboundMapper.updateMateOutbound(mateOutbound);
        }
        if (num == 1) {
            return auditMapper.updateAudit(audit1);
        } else {
            return num;
        }
    }

    /**
     * 同步修改订单审核对象
     *
     * @param map 需要删除的数据的条件
     * @return 结果
     */
    @Override
    public int deleteAuditWith(Map<String, Object> map) {
        return auditMapper.deleteAuditWith(map);
    }

    /**
     * 同步删除订单审核对象
     *
     * @param audit 需要删除的数据的条件
     * @return 结果
     */
    @Override
    public int updateAuditOther(Audit audit) {
        return auditMapper.updateAuditOther(audit);
    }

    /**
     * 删除订单审核对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteAuditByIds(String ids) {
        return auditMapper.deleteAuditByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除订单审核信息
     *
     * @param auditId 订单审核ID
     * @return 结果
     */
    @Override
    public int deleteAuditById(Long auditId) {
        return auditMapper.deleteAuditById(auditId);
    }

    /**
     * 销售订单 审核完成之后生成pdf
     *
     * @param saleorderId
     * @param deptId
     */
    @Override
    public void saleorderTopdf(Long saleorderId, Long deptId) {

//        int sbsoluteY = 470;
        int sbsoluteY = 400;
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("saleorderId", saleorderId);
        hashMap.put("deptId", deptId);
        SaleorderOrder saleorderOrder = saleorderMapper.selectSaleorderByIdMap(hashMap);
//        SaleorderOrder saleorderOrder = saleorderMapper.selectSaleorderById(hashMap);
        //供方 信息;
        Company purchaseData = companyMapper.selectByCompanyId(saleorderOrder.getDeptId());
        // CompanyInvoice purchaseInvoiceData = companyInvoiceMapper.selectByCompanyId(saleorderOrder.getDeptId());
        //需方 信息;
        Company demanderData = companyMapper.selectByCompanyId(saleorderOrder.getCompanyId());
        //  CompanyInvoice demanderInvoiceData = companyInvoiceMapper.selectByCompanyId(saleorderOrder.getCompanyId());

        String fileName = saleorderOrder.getSaleorderNum() + "(" + System.currentTimeMillis() + ")" + ".pdf";
        String downloadPath = RuoYiConfig.getDownloadPath();
        File d = new File(downloadPath);
        if (!d.exists()) {
            d.mkdir();
        }
        File file = new File(downloadPath + "/saleorderPdf");
        if (!file.exists()) {
            file.mkdir();
        }
        String destPath = downloadPath + "saleorderPdf/" + fileName;
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(destPath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        StringBuilder str = new StringBuilder();

        str.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
        str.append("<html lang=\"zh\" xmlns=\"http://www.w3.org/1999/xhtml\">");
        str.append("<head>\n" +
                "    <meta charset=\"UTF-8\"></meta>\n" +
                "    <title>Title</title>\n" +
                "</head>\n" +
                "<body style=\"font-family:SimSun;\">");

        str.append("<table width=\"680px\">");
        str.append("<tr>");
        str.append("<td style=\"color: black;font-size: 25px;font-weight: bold;\"><div align=\"center\">购销合同</div></td>");
        str.append("</tr>");
        str.append("</table>");
        str.append("<table width=\"830px\">");
        str.append("<tbody>");
        str.append("<tr>");
        str.append("<td width=\"50%\" align=\"left\"></td>");
        str.append("<td width=\"50%\" align=\"left\">合同编号：" + saleorderOrder.getSaleorderNum() + "</td></tr>");
        str.append("<tr><td>供货方（甲方）：" + sysDeptMapper.selectDeptById(saleorderOrder.getDeptId()).getDeptName() + "</td>");
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        str.append("<td>签订日期：" + fmt.format(saleorderOrder.getSaleorderDate()) + "</td></tr>");
        str.append("<tr><td>采购方（乙方）：" + sysDeptMapper.selectDeptById(saleorderOrder.getCompanyId()).getDeptName() + "</td>");
        //签订地点
        Map map = new HashMap();
        map.put("deptId", saleorderOrder.getDeptId());
        map.put("companyId", saleorderOrder.getCompanyId());
        map.put("gradeStatus", "02");
        CompanyOther companyOther = companyOtherMapper.selectByCompanyIdAndDeptId(map);
        if (companyOther == null) {
            new AjaxResult(AjaxResult.Type.ERROR, "您还没有建立与该合作单位的合作关系，请在基础信息-合作单位管理菜单模块建立合作关系。");
            throw new RuntimeException("您还没有建立与该合作单位的合作关系，请在基础信息-合作单位管理菜单模块建立合作关系。");
        }
        str.append("<td>签订地点：" + purchaseData.getRasCity() + "</td></tr>");
        str.append("</tbody></table>");

        str.append("<table width=\"830px\">\n" +
                "                <tbody>\n" +
                "                <tr>\n" +
                "                    <td width=\"100%\" >\n" +
                "                        一、货物名称及价格\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                </tbody>\n" +
                "            </table>");

        str.append("<table width=\"680px\" style=\"border-spacing: 0;border-collapse: collapse;\">\n" +
                "                <tr>\n" +
                "                    <td width=\"20%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            存货名称\n" +
                "                        </div>\n" +
                "                    </td >\n" +
                "                    <td width=\"15%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            生产厂家\n" +
                "                        </div>\n" +
                "                    </td >\n" +
                "                    <td width=\"12%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            规格型号\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                    <td width=\"6%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            单位\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                    <td width=\"8%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            数量\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                    <td width=\"10%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            含税单价\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                    <td width=\"12%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            含税金额\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                    <td width=\"12%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            备注\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                </tr>\n");
        //总数量
        int totalNum = 0;
        for (int i = 0; i < saleorderOrder.getSaleorderModels().size(); i++) {
            sbsoluteY = sbsoluteY - 18;
            SaleorderModel saleorderModel = saleorderOrder.getSaleorderModels().get(i);
            str.append("<tr>\n" +
                    "                    <td style=\"border:1px solid #000000;word-wrap:break-word;word-break:normal;font-size: 14px;\">" + saleorderModel.getProductName() + "</td>\n" +
                    "                    <td style=\"border:1px solid #000000;word-wrap:break-word;word-break:normal;font-size: 13px;\">" + saleorderModel.getManufacturerName() + "</td>\n" +
                    "                    <td style=\"border:1px solid #000000;word-wrap:break-word;word-break:normal;font-size: 14px;\">" + saleorderModel.getProductType() + "</td>\n" +
                    "                    <td style=\"border:1px solid #000000;word-wrap:break-word;word-break:normal;font-size: 14px;\">" + saleorderModel.getSalesUnit() + "</td>\n" +
                    "                    <td style=\"border:1px solid #000000;word-wrap:break-word;word-break:normal;font-size: 14px;\">" + saleorderModel.getNum() + "</td>\n" +
                    "                    <td style=\"border:1px solid #000000;word-wrap:break-word;word-break:normal;font-size: 14px;\">" + saleorderModel.getTaxPrice() + "</td>\n" +
                    "                    <td style=\"border:1px solid #000000;word-wrap:break-word;word-break:normal;font-size: 14px;\">" + saleorderModel.getTaxTotal() + "</td>\n" +
                    "                    <td style=\"border:1px solid #000000;\"></td>\n" +
                    "                </tr>");

            totalNum += saleorderOrder.getSaleorderModels().get(i).getNum();
        }
        str.append("                <tr>\n" +
                "                    <td style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 16px;\">\n" +
                "                            合计\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                    <td style=\"border:1px solid #000000;\"></td>\n" +
                "                    <td style=\"border:1px solid #000000;\"></td>\n" +
                "                    <td style=\"border:1px solid #000000;\"></td>\n" +
                "                    <td style=\"border:1px solid #000000;\">" + totalNum + "</td>\n" +
                "                    <td style=\"border:1px solid #000000;\"></td>\n" +
                "                    <td style=\"border:1px solid #000000;\">" + saleorderOrder.getSaleorderTaxamount() + "</td>\n" +
                "                    <td style=\"border:1px solid #000000;\"></td>\n" +
                "                </tr>\n" +
                "            </table>");

        //合计人民币
        BigDecimal taxamount = saleorderOrder.getSaleorderTaxamount();
        double saleorderTaxamount = taxamount.doubleValue();
        String upperCase = Util.upperCases(saleorderTaxamount);
//        String upperCase = Util.upperCase(saleorderTaxamount);
        str.append("<table width=\"850px\">\n" +
                "                <tbody>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;width:70%;;border: 0;!important;\">\n" +
                "                        合计人民币(大写)：" + upperCase + "\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                </tbody></table>\n");

        //合同约定项
        String contractTerms = companyOther.getContractTerms();
        if (contractTerms == null) {
            new AjaxResult(AjaxResult.Type.ERROR, "您与该公司的合同约定项为空,请先在基础信息-合作单位管理-编辑功能完善与该公司的合同约定项。");
            throw new RuntimeException("您与该公司的合同约定项为空,请先在基础信息-合作单位管理-编辑功能完善与该公司的合同约定项。");
        }
//        if (contractTerms == null) {
//            contractTerms = "二、交货时间：甲方收到货款后，当日或第二个工作日发货。\r\n" +
//                    "三、运输及费用承担方式：物流送货至乙方指定地址，甲方承担运费。\r\n" +
//                    "四、货款结算方式：乙方以电汇方式汇款，款到发货。开具13%增值税专用发票\r\n" +
//                    "五、质保与违约责任：须为生产企业原厂出品，原装进口，并符合中国医疗器械管理政策，否则无条件退货退款。\r\n" +
//                    "六、质量验收时效：请先验货，再签收物流。签收后视为验收合格。\r\n" +
//                    "七、本协议法律争议管辖地为山东省济南市。\r\n" +
//                    "八、合同一式两份，双方签字盖章后生效。扫描件具有同等法律效力。\r\n";
//        }

        //根据回车进行分割
        String[] contractTermsArr = new String[]{};
        contractTermsArr = contractTerms.split("\\r?\\n");
        str.append("<br></br>");
        str.append("<table width=\"850px\" id=\"contractTerms\">");
        for (int i = 0; i < contractTermsArr.length; i++) {
            sbsoluteY = sbsoluteY - 12;
            //每行81个字符
            String[] strings = Util.stringToArray(contractTermsArr[i]);
            String interception = Util.interception(strings, 80);
            //根据回车进行分割
            String[] split = interception.split("换行aaaaa");
            for (int j = 0; j < split.length; j++) {
                String s = split[j];
                System.out.println(s);
                str.append(s);
                str.append("<br></br>");
            }
        }
        str.append("</table>");
        str.append("<br></br>");

        //销售订单印章
        String purSeal = "";
        if (purchaseData.getElectronicSealUrl() != null && !"".equals(purchaseData.getElectronicSealUrl())) {
            purSeal = purchaseData.getElectronicSealUrl();
            purSeal = RuoYiConfig.getUploadPath() + purSeal.split("/profile/upload")[1];
        } else {
//            if (purchaseData.getSealUrl() != null && !"".equals(purchaseData.getSealUrl())) {
//                purSeal = purchaseData.getSealUrl();
//                purSeal = RuoYiConfig.getDownloadPath() + purSeal;
//            } else {
////                //生成电子印章到服务器
////                //自动生成一个印章 上传到服务器上
////                String socialCreditCode = purchaseData.getSocialCreditCode();
////                String imgname = socialCreditCode + ".png";
////                File pngfile = new File(downloadPath + "/seal");
////                if (!pngfile.exists()) {
////                    pngfile.mkdir();
////                }
////                String path = downloadPath + "seal/" + imgname;
////                //生成 印章照片
////                try {
////                    SealUtils.toSeal(sysDeptMapper.selectDeptById(purchaseData.getCompanyId()).getDeptName(), purchaseData.getSocialCreditCode(), path);
////                } catch (Exception e) {
////                    e.printStackTrace();
////                }
////
////                Company company2 = new Company();
////                company2.setSealUrl("/seal/" + imgname);
////                company2.setCompanyId(purchaseData.getCompanyId());
////                purSeal = RuoYiConfig.getDownloadPath() + "/seal/" + imgname;
////                //更新url
////                companyMapper.updateCompany(company2);
//            }
        }


        //销售订单印章
        String demanderSeal = "";
        if (demanderData.getElectronicSealUrl() != null && !"".equals(demanderData.getElectronicSealUrl())) {
            demanderSeal = demanderData.getElectronicSealUrl();
            demanderSeal = RuoYiConfig.getUploadPath() + demanderSeal.split("/profile/upload")[1];
        } else {
//            if (demanderData.getSealUrl() != null && !"".equals(demanderData.getSealUrl())) {
//                demanderSeal = demanderData.getSealUrl();
//                demanderSeal = RuoYiConfig.getDownloadPath() + demanderSeal;
//            } else {
////                //生成电子印章到服务器
////                //自动生成一个印章 上传到服务器上
////                String socialCreditCode = demanderData.getSocialCreditCode();
////                String imgname = socialCreditCode + ".png";
////                File pngfile = new File(downloadPath + "/seal");
////                if (!pngfile.exists()) {
////                    pngfile.mkdir();
////                }
////                String path = downloadPath + "seal/" + imgname;
////                //生成 印章照片
////                try {
////                    SealUtils.toSeal(sysDeptMapper.selectDeptById(demanderData.getCompanyId()).getDeptName(), demanderData.getSocialCreditCode(), path);
////                } catch (Exception e) {
////                    e.printStackTrace();
////                }
////
////                Company company3 = new Company();
////                company3.setSealUrl("/seal/" + imgname);
////                company3.setCompanyId(demanderData.getCompanyId());
////                demanderSeal = RuoYiConfig.getDownloadPath() + "/seal/" + imgname;
////                //更新url
////                companyMapper.updateCompany(company3);
//            }
        }
        String a = purSeal.replaceAll("\\\\", "/");
        String b = demanderSeal.replaceAll("\\\\", "/");

        str.append("<table width=\"700px\">\n" +
                "                <tbody>\n" +
                "                <tr>\n" +
                "                    <td width=\"50%\" align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        甲&nbsp;&nbsp;&nbsp;&nbsp;方：" + sysDeptMapper.selectDeptById(saleorderOrder.getDeptId()).getDeptName() + "\n" +
                "                    </td>\n" +
                "                    <td width=\"50%\" align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        乙&nbsp;&nbsp;&nbsp;&nbsp;方：" + sysDeptMapper.selectDeptById(saleorderOrder.getCompanyId()).getDeptName() + "\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" width=\"50%\" style=\"color: black;font-size: 16px;word-wrap:break-word;\">\n" +
                "                        地&nbsp;&nbsp;&nbsp;&nbsp;址：" + purchaseData.getRasProvince() + purchaseData.getRasCity() + purchaseData.getRasDistrict() + purchaseData.getRasAddress() + "\n" +
                "                    </td>\n" +
                "                    <td align=\"left\" width=\"50%\" style=\"color: black;font-size: 16px;word-wrap:break-word;\">\n" +
                "                        地&nbsp;&nbsp;&nbsp;&nbsp;址：" + demanderData.getRasProvince() + demanderData.getRasCity() + demanderData.getRasDistrict() + demanderData.getRasAddress() + "\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        邮&nbsp;&nbsp;&nbsp;&nbsp;编：\n" +
                "                    </td>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        邮&nbsp;&nbsp;&nbsp;&nbsp;编：\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        电&nbsp;&nbsp;&nbsp;&nbsp;话：" + purchaseData.getCorporateRegisterPhone() + "\n" +
                "                    </td>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        电&nbsp;&nbsp;&nbsp;&nbsp;话：" + demanderData.getCorporateRegisterPhone() + "\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        统一社会信用代码：" + purchaseData.getSocialCreditCode() + "\n" +
                "                    </td>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        统一社会信用代码：" + demanderData.getSocialCreditCode() + "\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        开&nbsp;&nbsp;&nbsp;&nbsp;户：" + purchaseData.getDepositBank() + "\n" +
                "                    </td>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        开&nbsp;&nbsp;&nbsp;&nbsp;户：" + formatString(demanderData.getDepositBank()) + "\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        账&nbsp;&nbsp;&nbsp;&nbsp;号：" + purchaseData.getBankNumber() + "\n" +
                "                    </td>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        账&nbsp;&nbsp;&nbsp;&nbsp;号：" + demanderData.getBankNumber() + "\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        签约代表：" + purchaseData.getCorporateRepresentative() + "\n" +
                "                    </td>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        签约代表：" + demanderData.getCorporateRepresentative() + "\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                </tbody>\n" +
                "            </table>");
        str.append("</body></html>");

        String[] split = destPath.split("nyterp");
        SaleorderOrder saleorderOrder1 = new SaleorderOrder();
        saleorderOrder1.setSaleorderId(saleorderOrder.getSaleorderId());

        saleorderOrder1.setPdfUrl("/saleorderPdf/销售合同" + fileName);
        saleorderMapper.updateSaleorderPdf(saleorderOrder1);

        //生成PDF
        HtmlToPdf.createPdfByHtml(fileOutputStream, str.toString());

        //判断 该两个公司 是否 上传了 印章  如果没有上传 则自动生成一个印章
        String purchaseSealUrl = "";
        String saleSealUrl = "";
        //供方
        if (!"".equals(purchaseData.getElectronicSealUrl()) && purchaseData.getElectronicSealUrl() != null) {
            purchaseSealUrl = purchaseData.getElectronicSealUrl();
        } else {
//            if (!"".equals(purchaseData.getSealUrl()) && purchaseData.getSealUrl() != null) {
//                purchaseSealUrl = purchaseData.getSealUrl();
//            } else {
////                //自动生成一个印章 上传到服务器上
////                String socialCreditCode = purchaseData.getSocialCreditCode();
////                String imgname = socialCreditCode + ".png";
////                String pngPath = RuoYiConfig.getDownloadPath();
////                File file1 = new File(pngPath);
////                if (!file1.exists()) {
////                    file1.mkdir();
////                }
////                File pngfile = new File(pngPath + "/seal");
////                if (!pngfile.exists()) {
////                    pngfile.mkdir();
////                }
////                String path = pngPath + "seal/" + imgname;
////                //生成 印章照片
////                try {
////                    SealUtils.toSeal(sysDeptMapper.selectDeptById(purchaseData.getCompanyId()).getDeptName(), purchaseData.getSocialCreditCode(), path);
////                } catch (Exception e) {
////                    e.printStackTrace();
////                }
////
////                Company company = new Company();
////                company.setSealUrl("/seal/" + imgname);
////                company.setCompanyId(purchaseData.getCompanyId());
////                purchaseSealUrl = "/seal/" + imgname;
////                //更新url
////                companyMapper.updateCompany(company);
//            }
        }

        //需方  也就是采购
        if (!"".equals(demanderData.getElectronicSealUrl()) && demanderData.getElectronicSealUrl() != null) {
            saleSealUrl = demanderData.getElectronicSealUrl();
        } else {
//            if (!"".equals(demanderData.getSealUrl()) && demanderData.getSealUrl() != null) {
//                saleSealUrl = demanderData.getSealUrl();
//            } else {
////                //自动生成一个印章 上传到服务器上
////                String socialCreditCode = demanderData.getSocialCreditCode();
////                String imgname = socialCreditCode + ".png";
////                String pngPath = RuoYiConfig.getDownloadPath();
////                File file1 = new File(pngPath);
////                if (!file1.exists()) {
////                    file1.mkdir();
////                }
////                File pngfile = new File(pngPath + "/seal");
////                if (!pngfile.exists()) {
////                    pngfile.mkdir();
////                }
////                String path = pngPath + "seal/" + imgname;
////                //生成 印章照片
////                try {
////                    SealUtils.toSeal(sysDeptMapper.selectDeptById(demanderData.getCompanyId()).getDeptName(), demanderData.getSocialCreditCode(), path);
////                } catch (Exception e) {
////                    e.printStackTrace();
////                }
////
////                //String[] split1 = path.split("nyterp");
////                Company company = new Company();
////                company.setSealUrl("/seal/" + imgname);
//////                company.setSealUrl(split1[1]);
//////                saleSealUrl = split1[1];
////                company.setCompanyId(demanderData.getCompanyId());
////                saleSealUrl = "/seal/" + imgname;
////                //更新url
////                companyMapper.updateCompany(company);
//            }
        }

        String downloadPath1 = RuoYiConfig.getDownloadPath();
        File file1 = new File(downloadPath1);
        if (!file1.exists()) {
            file1.mkdir();
        }

        String uploadPath = RuoYiConfig.getUploadPath();
        String purUrl = "";
        String saleUrl = "";

        String purImgPath = "";
        String saleImgPath = "";
        if (!"".equals(purchaseData.getElectronicSealUrl()) && purchaseData.getElectronicSealUrl() != null) {
            purUrl = purchaseSealUrl;
            String[] split1 = purUrl.split("/profile/upload");
            purImgPath = uploadPath + split1[1];
        } else {
            purImgPath = downloadPath1 + purchaseSealUrl;
        }
        if (!"".equals(demanderData.getElectronicSealUrl()) && demanderData.getElectronicSealUrl() != null) {
            saleUrl = saleSealUrl;
            String[] split1 = saleUrl.split("/profile/upload");
            saleImgPath = uploadPath + split1[1];
        } else {
            saleImgPath = downloadPath1 + saleSealUrl;
        }

        String fileStr = downloadPath1 + "saleorderPdf/" + fileName;
        String fileStr1 = downloadPath1 + "saleorderPdf/2" + fileName;
        String fileStr3 = downloadPath1 + "saleorderPdf/销售合同" + fileName;

        try {
            if (!purchaseSealUrl.equals("")) {
                //左边照片
                ImgToPdf.imgToPdfLeft(fileStr, fileStr1, purImgPath, sbsoluteY);
            } else {
                ImgToPdf.imgToPdf(fileStr, fileStr1);
            }
            if (!saleSealUrl.equals("")) {
                //右边照片
                ImgToPdf.imgToPdfRight(fileStr1, fileStr3, saleImgPath, sbsoluteY);
            } else {
                ImgToPdf.imgToPdf(fileStr1, fileStr3);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

//        try {
//            ImgToPdf.imgToPdf(fileStr, fileStr3);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        try {
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //删除fileStr fileStr1
        File filePath = new File(fileStr);
        filePath.delete();
        File filePath1 = new File(fileStr1);
        filePath1.delete();

    }

    public static String formatString(String str) {
        if (str == null) return "";
        int maxLength = 20;
        if (str.length() <= maxLength) return str;

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            sb.append(str.charAt(i));
            if ((i+1) % 20 == 0) {
                sb.append("\n");
            }
        }
        return sb.toString();
    }

    /**
     * 采购订单 审核完成之后生成pdf
     *
     * @param purchaseId
     * @param deptId
     */
    @Override
    public void purchaseTopdf(Long purchaseId, Long deptId) {
//        int sbsoluteY = 470;
        int sbsoluteY = 400;
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("purchaseId", purchaseId);
        hashMap.put("deptId", deptId);
        PurchaseOrder purchaseOrder = purchaseOrderMapper.selectPurchaseOrderByMap(hashMap);
        //供方 信息;
        Company purchaseData = companyMapper.selectByCompanyId(purchaseOrder.getSupplierId());
        //CompanyInvoice purchaseInvoiceData = companyInvoiceMapper.selectByCompanyId(purchaseOrder.getSupplierId());
        //需方 信息;
        Company demanderData = companyMapper.selectByCompanyId(purchaseOrder.getDeptId());

        //CompanyInvoice demanderInvoiceData = companyInvoiceMapper.selectByCompanyId(purchaseOrder.getDeptId());

        String fileName = purchaseOrder.getPurchaseNum() + "(" + System.currentTimeMillis() + ")" + ".pdf";
        String downloadPath = RuoYiConfig.getDownloadPath();
        File file1 = new File(downloadPath);
        if (!file1.exists()) {
            file1.mkdir();
        }
        File file = new File(downloadPath + "/purchaseTopdf");
        if (!file.exists()) {
            file.mkdir();
        }
        String destPath = downloadPath + "purchaseTopdf/" + fileName;
        String aaaa = downloadPath + "purchaseTopdf/";
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(destPath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        StringBuilder str = new StringBuilder();
        str.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
        str.append("<html lang=\"zh\" xmlns=\"http://www.w3.org/1999/xhtml\">");
        str.append("<head>\n" +
                "    <meta charset=\"UTF-8\"></meta>\n" +
                "    <title>Title</title>\n" +
                "</head>\n" +
                "<body style=\"font-family:SimSun;\">");

        str.append("<table width=\"680px\">");
        str.append("<tr>");
        str.append("<td style=\"color: black;font-size: 25px;font-weight: bold;\"><div align=\"center\">采购合同</div></td>");
        str.append("</tr>");
        str.append("</table>");

        str.append("<table width=\"850px\">");
        str.append("<tbody>");
        str.append("<tr>");
        str.append("<td width=\"50%\" align=\"left\"></td>");
        str.append("<td width=\"50%\" align=\"left\">合同编号：" + purchaseOrder.getPurchaseNum() + "</td></tr>");
        str.append("<tr><td>供货方（甲方）：" + sysDeptMapper.selectDeptById(purchaseOrder.getSupplierId()).getDeptName() + "</td>");
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        str.append("<td>签订日期：" + fmt.format(purchaseOrder.getPurchaseDate()) + "</td></tr>");
        str.append("<tr><td>采购方（乙方）：" + sysDeptMapper.selectDeptById(purchaseOrder.getDeptId()).getDeptName() + "</td>");
        //签订地点
        Map map = new HashMap();
        map.put("deptId", purchaseOrder.getDeptId());
        map.put("companyId", purchaseOrder.getSupplierId());
        map.put("gradeStatus", "02");
        CompanyOther companyOther = companyOtherMapper.selectByCompanyIdAndDeptId(map);
        if (companyOther == null) {
            new AjaxResult(AjaxResult.Type.ERROR, "您还没有建立与该合作单位的合作关系，请在基础信息-合作单位管理菜单模块建立合作关系。");
            throw new RuntimeException("您还没有建立与该合作单位的合作关系，请在基础信息-合作单位管理菜单模块建立合作关系。");
        }
        str.append("<td>签订地点：" + purchaseData.getRasCity() + "</td></tr>");
        str.append("</tbody></table>");

        str.append("<table width=\"830px\">\n" +
                "                <tbody>\n" +
                "                <tr>\n" +
                "                    <td width=\"100%\" >\n" +
                "                        一、货物名称及价格\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                </tbody>\n" +
                "            </table>");

        str.append("<table width=\"680px\" style=\"border-spacing: 0;border-collapse: collapse;\">\n" +
                "                <tr>\n" +
                "                    <td width=\"20%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            存货名称\n" +
                "                        </div>\n" +
                "                    </td >\n" +
                "                    <td width=\"15%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            生产厂家\n" +
                "                        </div>\n" +
                "                    </td >\n" +
                "                    <td width=\"12%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            规格型号\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                    <td width=\"6%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            单位\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                    <td width=\"8%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            数量\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                    <td width=\"10%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            含税单价\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                    <td width=\"12%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            含税金额\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                    <td width=\"12%\" style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 15px;\">\n" +
                "                            备注\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                </tr>\n");
        //总数量
        int totalNum = 0;
        for (int i = 0; i < purchaseOrder.getPurchaseModel().size(); i++) {
            sbsoluteY = sbsoluteY - 18;
            PurchaseModel purchaseModel = purchaseOrder.getPurchaseModel().get(i);
            str.append("<tr>\n" +
                    "                    <td style=\"border:1px solid #000000;word-wrap:break-word;word-break:normal;font-size: 14px;\">" + purchaseModel.getProductName() + "</td>\n" +
                    "                    <td style=\"border:1px solid #000000;word-wrap:break-word;word-break:normal;font-size: 13px;\">" + purchaseModel.getManufacturerName() + "</td>\n" +
                    "                    <td style=\"border:1px solid #000000;word-wrap:break-word;word-break:normal;font-size: 14px;\">" + purchaseModel.getProductType() + "</td>\n" +
                    "                    <td style=\"border:1px solid #000000;word-wrap:break-word;word-break:normal;font-size: 14px;\">" + purchaseModel.getUnit() + "</td>\n" +
                    "                    <td style=\"border:1px solid #000000;word-wrap:break-word;word-break:normal;font-size: 14px;\">" + purchaseModel.getPurchaseNum() + "</td>\n" +
                    "                    <td style=\"border:1px solid #000000;word-wrap:break-word;word-break:normal;font-size: 14px;\">" + purchaseModel.getTaxPrice() + "</td>\n" +
                    "                    <td style=\"border:1px solid #000000;word-wrap:break-word;word-break:normal;font-size: 14px;\">" + purchaseModel.getTaxTotal() + "</td>\n" +
                    "                    <td style=\"border:1px solid #000000;\"></td>\n" +
                    "                </tr>");

            totalNum += purchaseOrder.getPurchaseModel().get(i).getPurchaseNum();
        }
        str.append("                <tr>\n" +
                "                    <td style=\"border:1px solid #000000;\">\n" +
                "                        <div align=\"center\" style=\"color: black;font-size: 16px;\">\n" +
                "                            合计\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                    <td style=\"border:1px solid #000000;\"></td>\n" +
                "                    <td style=\"border:1px solid #000000;\"></td>\n" +
                "                    <td style=\"border:1px solid #000000;\"></td>\n" +
                "                    <td style=\"border:1px solid #000000;\">" + totalNum + "</td>\n" +
                "                    <td style=\"border:1px solid #000000;\"></td>\n" +
                "                    <td style=\"border:1px solid #000000;\">" + purchaseOrder.getTaxAmount() + "</td>\n" +
                "                    <td style=\"border:1px solid #000000;\"></td>\n" +
                "                </tr>\n" +
                "            </table>");

        //合计人民币
        BigDecimal taxamount = purchaseOrder.getTaxAmount();
        double saleorderTaxamount = taxamount.doubleValue();
//        String upperCase = Util.upperCase(saleorderTaxamount);
        String upperCase = Util.upperCases(saleorderTaxamount);
        str.append("<table width=\"850px\">\n" +
                "                <tbody>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;width:70%;;border: 0;!important;\">\n" +
                "                        合计人民币(大写)：" + upperCase + "\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                </tbody></table>\n");

        //合同约定项
        String contractTerms = companyOther.getContractTerms();
        if (contractTerms == null) {
            new AjaxResult(AjaxResult.Type.ERROR, "您与该公司的合同约定项为空,请先在基础信息-合作单位管理-编辑功能完善与该公司的合同约定项。");
            throw new RuntimeException("您与该公司的合同约定项为空,请先在基础信息-合作单位管理-编辑功能完善与该公司的合同约定项。");
        }
//        if (contractTerms == null) {
//            contractTerms = "二、交货时间：甲方收到货款后，当日或第二个工作日发货。\n" +
//                    "三、运输及费用承担方式：物流送货至乙方指定地址，甲方承担运费。\n" +
//                    "四、货款结算方式：乙方以电汇方式汇款，款到发货。开具13%增值税专用发票\n" +
//                    "五、质保与违约责任：须为生产企业原厂出品，原装进口，并符合中国医疗器械管理政策，否则无\n" +
//                    "条件退货退款。\n" +
//                    "六、质量验收时效：请先验货，再签收物流。签收后视为验收合格。\n" +
//                    "七、本协议法律争议管辖地为山东省济南市。\n" +
//                    "八、合同一式两份，双方签字盖章后生效。扫描件具有同等法律效力。";
//        }

        //根据回车进行分割
        String[] contractTermsArr = new String[]{};
        contractTermsArr = contractTerms.split("\\r?\\n");

        str.append("<br></br>");
        str.append("<table width=\"850px\" id=\"contractTerms\">");
        for (int i = 0; i < contractTermsArr.length; i++) {
            sbsoluteY = sbsoluteY - 12;
            //每行81个字符
            String[] strings = Util.stringToArray(contractTermsArr[i]);
            String interception = Util.interception(strings, 80);
            //根据回车进行分割
            String[] split = interception.split("换行aaaaa");
            for (int j = 0; j < split.length; j++) {
                String s = split[j];
                System.out.println(s);
                str.append(s);
                str.append("<br></br>");
            }
        }
        str.append("</table>");
        str.append("<br></br>");

        str.append("<table width=\"680px\">\n" +
                "                <tbody>\n" +
                "                <tr>\n" +
                "                    <td width=\"45%\" align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        甲&nbsp;&nbsp;&nbsp;&nbsp;方：" + sysDeptMapper.selectDeptById(purchaseOrder.getSupplierId()).getDeptName() + "\n" +
                "                    </td>\n" +
                "                    <td width=\"45%\" align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        乙&nbsp;&nbsp;&nbsp;&nbsp;方：" + sysDeptMapper.selectDeptById(purchaseOrder.getDeptId()).getDeptName() + "\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;white-space:normal;word-break:break-all;\">\n" +
                "                        地&nbsp;&nbsp;&nbsp;&nbsp;址：" + purchaseData.getRasProvince() + purchaseData.getRasCity() + purchaseData.getRasDistrict() + purchaseData.getRasAddress() +
                "                    </td>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;white-space:normal;word-break:break-all;\">\n" +
                "                        地&nbsp;&nbsp;&nbsp;&nbsp;址：" + demanderData.getRasProvince() + demanderData.getRasCity() + demanderData.getRasDistrict() + demanderData.getRasAddress() +
                "                    </td>\n" +
                "                </tr>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        邮&nbsp;&nbsp;&nbsp;&nbsp;编：\n" +
                "                    </td>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        邮&nbsp;&nbsp;&nbsp;&nbsp;编：\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        电&nbsp;&nbsp;&nbsp;&nbsp;话：" + purchaseData.getCorporateRegisterPhone() + "\n" +
                "                    </td>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        电&nbsp;&nbsp;&nbsp;&nbsp;话：" + demanderData.getCorporateRegisterPhone() + "\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        统一社会信用代码：" + purchaseData.getSocialCreditCode() + "\n" +
                "                    </td>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        统一社会信用代码：" + demanderData.getSocialCreditCode() + "\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        开&nbsp;&nbsp;&nbsp;&nbsp;户：" + purchaseData.getDepositBank() + "\n" +
                "                    </td>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        开&nbsp;&nbsp;&nbsp;&nbsp;户：" + demanderData.getDepositBank() + "\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        账&nbsp;&nbsp;&nbsp;&nbsp;号：" + purchaseData.getBankNumber() + "\n" +
                "                    </td>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        账&nbsp;&nbsp;&nbsp;&nbsp;号：" + demanderData.getBankNumber() + "\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                <tr>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        签约代表：" + purchaseData.getCorporateRepresentative() + "\n" +
                "                    </td>\n" +
                "                    <td align=\"left\" style=\"color: black;font-size: 16px;\">\n" +
                "                        签约代表：" + demanderData.getCorporateRepresentative() + "\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                </tbody>\n" +
                "            </table>");

        str.append("</body></html>");

        PurchaseOrder purchaseOrder1 = new PurchaseOrder();
        purchaseOrder1.setPurchaseId(purchaseOrder.getPurchaseId());
        String[] split = destPath.split("nyterp");

        String string = aaaa + "sale" + fileName;
        String[] split3 = string.split("nyterp");
        purchaseOrder1.setPdfUrl("/purchaseTopdf/采购合同" + fileName);
        purchaseOrderMapper.updatePurchasePdf(purchaseOrder1);
        //生成PDF
        HtmlToPdf.createPdfByHtml(fileOutputStream, str.toString());

        //判断 该两个公司 是否 上传了 印章  如果没有上传 则自动生成一个印章
        String purchaseSealUrl = "";
        String saleSealUrl = "";
        //供方
        if (!"".equals(purchaseData.getElectronicSealUrl()) && purchaseData.getElectronicSealUrl() != null) {
            purchaseSealUrl = purchaseData.getElectronicSealUrl();
        } else {
//            if (!"".equals(purchaseData.getSealUrl()) && purchaseData.getSealUrl() != null) {
//                purchaseSealUrl = purchaseData.getSealUrl();
//            } else {
////                //自动生成一个印章 上传到服务器上
////                String socialCreditCode = purchaseData.getSocialCreditCode();
////                String imgname = socialCreditCode + ".png";
////                String pngPath = RuoYiConfig.getDownloadPath();
////                File file2 = new File(pngPath);
////                if (!file2.exists()) {
////                    file2.mkdir();
////                }
////                File pngfile = new File(pngPath + "/seal");
////                if (!pngfile.exists()) {
////                    pngfile.mkdir();
////                }
////                String path = pngPath + "seal/" + imgname;
////                //生成 印章照片
////                try {
////                    SealUtils.toSeal(sysDeptMapper.selectDeptById(purchaseData.getCompanyId()).getDeptName(), purchaseData.getSocialCreditCode(), path);
////                } catch (Exception e) {
////                    e.printStackTrace();
////                }
////
////                Company company = new Company();
////                company.setSealUrl("/seal/" + imgname);
////                company.setCompanyId(purchaseData.getCompanyId());
////                //更新url
////                purchaseSealUrl = "/seal/" + imgname;
////                companyMapper.updateCompany(company);
//            }
        }

        //需方  也就是采购
        if (!"".equals(demanderData.getElectronicSealUrl()) && demanderData.getElectronicSealUrl() != null) {
            saleSealUrl = demanderData.getElectronicSealUrl();
        } else {
//            if (!"".equals(demanderData.getSealUrl()) && demanderData.getSealUrl() != null) {
//                saleSealUrl = demanderData.getSealUrl();
//            } else {
////                //自动生成一个印章 上传到服务器上
////                String socialCreditCode = demanderData.getSocialCreditCode();
////                String imgname = socialCreditCode + ".png";
////                String pngPath = RuoYiConfig.getDownloadPath();
////                File pngfile = new File(pngPath + "/seal");
////                if (!pngfile.exists()) {
////                    pngfile.mkdir();
////                }
////                String path = pngPath + "seal/" + imgname;
////                //生成 印章照片
////                try {
////                    SealUtils.toSeal(sysDeptMapper.selectDeptById(demanderData.getCompanyId()).getDeptName(), demanderData.getSocialCreditCode(), path);
////                } catch (Exception e) {
////                    e.printStackTrace();
////                }
////                Company company = new Company();
////                company.setSealUrl("/seal/" + imgname);
////                company.setCompanyId(demanderData.getCompanyId());
////                //更新url
////                saleSealUrl = "/seal/" + imgname;
////                companyMapper.updateCompany(company);
//            }
        }

        String downloadPath1 = RuoYiConfig.getDownloadPath();
        String uploadPath = RuoYiConfig.getUploadPath();
        String purUrl = "";
        String saleUrl = "";

        String purImgPath = "";
        String saleImgPath = "";

        if (!"".equals(purchaseData.getElectronicSealUrl()) && purchaseData.getElectronicSealUrl() != null) {
            purUrl = purchaseSealUrl;
            String[] split1 = purUrl.split("/profile/upload");
            purImgPath = uploadPath + split1[1];
        } else {
            purImgPath = downloadPath1 + purchaseSealUrl;
        }

        if (!"".equals(demanderData.getElectronicSealUrl()) && demanderData.getElectronicSealUrl() != null) {
            saleUrl = saleSealUrl;
            String[] split1 = saleUrl.split("/profile/upload");
            saleImgPath = uploadPath + split1[1];
        } else {
            saleImgPath = downloadPath1 + saleSealUrl;
        }

        String fileStr = downloadPath1 + "purchaseTopdf/" + fileName;
        String fileStr1 = downloadPath1 + "purchaseTopdf/2" + fileName;
        String fileStr3 = downloadPath1 + "purchaseTopdf/采购合同" + fileName;

        try {
            if (!purchaseSealUrl.equals("")) {
                //左边照片
                ImgToPdf.imgToPdfLeft(fileStr, fileStr1, purImgPath, sbsoluteY);
            } else {
                ImgToPdf.imgToPdf(fileStr, fileStr1);
            }
            if (!saleSealUrl.equals("")) {
                //右边照片
                ImgToPdf.imgToPdfRight(fileStr1, fileStr3, saleImgPath, sbsoluteY);
            } else {
                ImgToPdf.imgToPdf(fileStr1, fileStr3);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        try {
//            ImgToPdf.imgToPdf(fileStr, fileStr3);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        //删除fileStr fileStr1
        File filePath1 = new File(fileStr);
        if (filePath1.exists()) {
            filePath1.delete();
        }
        File filePath2 = new File(fileStr1);
        if (filePath2.exists()) {
            filePath2.delete();
        }


    }

    /**
     * 退回审核
     *
     * @param auditId 审核表主键
     * @return 结果
     */
    @Override
    public int returnReview(Long auditId) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Audit audit = auditMapper.selectAuditById(auditId);
        Long deptId = sysUser.getCompanyId();
        Long orderId = audit.getOrderId();
        String orderType = audit.getOrderType();
        String auditStatus = audit.getAuditStatus();
        audit.setAuditRemark("");
        audit.setAuditStatus("0");
        int num = 0;
        if (orderType.equals("1")) {
            //采购订单
            PurchaseOrder purchaseOrder = purchaseOrderMapper.selectPurchaseOrderById(orderId);
            purchaseOrder.setPurchaseStatus("0");

            String purchaseNum = purchaseOrder.getPurchaseNum();
            Long supplierId = purchaseOrder.getDeptId();
            HashMap<String, Object> hashMap = new HashMap<>();
//            hashMap.put("saleorderNum", purchaseNum);
//            hashMap.put("companyId", supplierId);
            hashMap.put("purchaseId", purchaseOrder.getPurchaseId());
            hashMap.put("saleorderStatus", "!=2");
            SaleorderOrder saleorderOrder = saleorderMapper.selectSaleorderByMap(hashMap);
            purchaseOrder.setUpdateBy(sysUser.getNickName());
            if (saleorderOrder != null) {
                return 0;
            }
            num = purchaseOrderMapper.updatePurchaseOrder(purchaseOrder);
        } else if (orderType.equals("0")) {
            //销售订单
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("saleorderId", orderId);
            hashMap.put("deptId", sysUser.getCompanyId());
            SaleorderOrder saleorderOrder = saleorderMapper.selectSaleorderById(hashMap);
            saleorderOrder.setSaleorderStatus("0");
            if (saleorderOrder.getAbandonment().equals("1")) {
                return 0;
            }
            int i = 0;
            for (SaleorderModel saleorderModel : saleorderOrder.getSaleorderModels()) {
                String executeStatus = saleorderModel.getExecuteStatus();
                int executeNum = saleorderModel.getExecuteNum();
                int remainingNum = saleorderModel.getRemainingNum();
                if (!executeStatus.equals("0") || 0 != executeNum) {
                    i++;
                }
            }
            if (i != 0) {
                return 0;
            }
            saleorderOrder.setUpdateBy(sysUser.getNickName());
            num = saleorderMapper.updateSaleorder(saleorderOrder);
            if ("1".equals(audit.getAuditStatus()) && saleorderOrder.getPurchaseId() != null) {
                PurchaseOrder purchaseOrder = new PurchaseOrder();
                purchaseOrder.setPurchaseFlag("1");
                purchaseOrder.setIsCreateSale(1);
                purchaseOrder.setUpdateBy(sysUser.getNickName());
                purchaseOrder.setPurchaseId(saleorderOrder.getPurchaseId());
                purchaseOrderMapper.updatePurchaseOrder(purchaseOrder);
            } else {
                PurchaseOrder purchaseOrder = new PurchaseOrder();
                purchaseOrder.setPurchaseId(saleorderOrder.getPurchaseId());
                purchaseOrder.setIsCreateSale(0);
                purchaseOrder.setUpdateBy(sysUser.getNickName());
                purchaseOrderMapper.updatePurchaseOrder(purchaseOrder);
            }
        } else if (orderType.equals("2")) {
            //采购入库
            ProcurementOrder procurementOrder = procurementOrderMapper.selectProcurementById(orderId);
            if ("1".equals(procurementOrder.getIsReturn())) {
                throw new RuntimeException("该订单已有退货,不允许退回审核");
            }
            procurementOrder.setProcurementWarehousingId(orderId);
            procurementOrder.setAuditTime(DateUtils.getNowDate());
            procurementOrder.setProcurementStatus(audit.getAuditStatus());

            List<ProcurementModel> procurementModelList = procurementOrderMapper.selectProcurementModelById(orderId);
            for (ProcurementModel procurementModel : procurementModelList) {
                procurementModel.setAllNum(-procurementModel.getAllNum());
            }
            procurementOrder.setProcurementModelList(procurementModelList);
            if (auditStatus.equals("1")) {
                calculation(procurementOrder);
            }
            for (ProcurementModel procurementModel : procurementModelList) {
                procurementModel.setWarehousingAmount(-procurementModel.getWarehousingAmount());
            }
            procurementOrder.setProcurementModelList(procurementModelList);
            procurementOrder.setUpdateBy(sysUser.getNickName());
            num = procurementOrderMapper.updateProcurementOrder(procurementOrder);

            //若是销货单入库 则删除 销货单入库表
            if (procurementOrder.getSaleGoodsId() != null) {
                enterstockMapper.deleteEnterStockOrder(procurementOrder.getProcurementWarehousingId());
                enterstockMapper.deleteEnterStockModer(procurementOrder.getProcurementWarehousingId());
            }

            AmountDetailed amountDetailed = new AmountDetailed();
            //订单金额
            BigDecimal purchaseAmount = procurementOrder.getPurchaseAmount();
            //订单金额(含税)
            BigDecimal taxAmount = procurementOrder.getTaxAmount();
            BigDecimal bigDecimal = new BigDecimal(0);

            amountDetailed.setCreateBy(sysUser.getNickName());
            amountDetailed.setCompanyId(sysUser.getCompanyId());
            amountDetailed.setOrderId(audit.getOrderId());
            amountDetailed.setOrderType("0");
            //amountDetailed.setTaxAmount(bigDecimal.subtract(purchaseAmount));
            amountDetailed.setTaxTotal(bigDecimal.subtract(taxAmount));

            amountDetailedMapper.insertAmountDetailed(amountDetailed);

            inventoryAmountMapper.deleteInventorAmount(auditId);

        } else if (orderType.equals("3")) {
            //销货单
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("saleGoodsId", orderId);
            SaleGoodsOrder saleGoodsOrder = saleGoodsMapper.selectSaleGoodsByIds(hashMap);
            if ("1".equals(saleGoodsOrder.getIsReturn())) {
                throw new RuntimeException("该订单已有退货,不允许退回审核");
            }
            if (saleGoodsOrder != null && saleGoodsOrder.getIsWarehousingOrder() == 1) {
                return 0;
            }
            List<Long> list = new ArrayList<>();
            if (saleGoodsOrder.getSaleGoodsModels().size() != 0) {
                for (SaleGoodsModel saleGoodsModel : saleGoodsOrder.getSaleGoodsModels()) {
                    List<SaleorderModel> lisat = saleGoodsMapper.selectNum(saleGoodsModel);
                    for (SaleorderModel saleorderModel : lisat) {
                        saleorderModel.setAllNum(saleorderModel.getAllNum() + saleGoodsModel.getAllNum());
                        saleorderModel.setRemainingNum(saleorderModel.getRemainingNum() + saleGoodsModel.getAllNum());
                        saleorderModel.setExecuteNum(saleorderModel.getExecuteNum() - saleGoodsModel.getAllNum());
                        saleGoodsMapper.updateSaleOrderModel(saleorderModel);
                    }
                    Long saleGoodsModelId = saleGoodsModel.getSaleGoodsModelId();
                    list.add(saleGoodsModelId);
                }
            }
            if (list.size() != 0) {
                List<SaleGoodsModel> saleGoodsModels = saleGoodsMapper.selectSaleGoodsModelByListsInvoice(list);
                if (saleGoodsModels.size() != 0) {
                    throw new RuntimeException("该订单已有开票信息,不允许退回审核");
                }
//                List<SaleGoodsModel> saleGoodsModels = saleGoodsMapper.selectSaleGoodsModelByLists(list);
//                if (saleGoodsModels.size() != 0) {
//                    for (SaleGoodsModel saleGoodsModel : saleGoodsModels) {
//                        int remainingNum = saleGoodsModel.getRemainingNum();
//                        if (remainingNum == 0) {
//                            throw new RuntimeException("该订单已有开票信息,不允许退回审核");
//                        }
//                    }
//                }
            }
            saleGoodsOrder.setSaleGoodsStatus(audit.getAuditStatus());
            saleGoodsOrder.setUpdateBy(sysUser.getNickName());

            if (auditStatus.equals("1")) {
                outboundAudit(saleGoodsOrder);
            }
            //如果该销货单 选择的销售订单选择了对方公司做的采购订单 将该采购订单的出库数量 减回去
//            List<PurchaseModel> retrunOutNum = saleGoodsMapper.selectPurModelBeforOutNum(orderId);
//
//            if (retrunOutNum!=null){
//                for (int i = 0; i < retrunOutNum.size(); i++) {
//                    purchaseOrderMapper.updatePurchaseModel(retrunOutNum.get(i));
//                }
//            }

            num = saleGoodsMapper.updateSaleGoodsOrder(saleGoodsOrder);

//            AmountDetailed amountDetailed = new AmountDetailed();
//            HashMap<String, Object> map = new HashMap<>();
//            map.put("saleGoodsId", orderId);
//            BigDecimal saleGoodsTaxamount = saleGoodsOrder.getSaleGoodsTaxamount();
//            BigDecimal saleGoodsAmount = saleGoodsOrder.getSaleGoodsAmount();
//            BigDecimal bigDecimal = new BigDecimal(0);
//            amountDetailed.setCreateBy(WXShiroUtils.getSysUser().getUserName());
//            amountDetailed.setCompanyId(WXShiroUtils.getSysUser().getCompanyId());
//            amountDetailed.setOrderId(audit.getOrderId());
//            amountDetailed.setOrderType("1");
//            amountDetailed.setTaxAmount(bigDecimal.add(saleGoodsAmount));
//            amountDetailed.setTaxTotal(bigDecimal.add(saleGoodsTaxamount));
//            amountDetailedMapper.insertAmountDetailed(amountDetailed);

            InventoryAmount inventoryAmount = new InventoryAmount();
            inventoryAmount.setAuditId(auditId);
            inventoryAmount.setDeptId(sysUser.getCompanyId());
            inventoryAmount.setOrderId(orderId);
            returnInventorAmount(inventoryAmount);

        } else if (orderType.equals("4")) {
            //月度盘点
            MonthlyInventoryLog monthlyInventoryLog = monthlyInventoryMapper.selectMonthlyInventoryLogById(orderId);
            monthlyInventoryLog.setLogId(audit.getOrderId());
            monthlyInventoryLog.setChangeNum(-monthlyInventoryLog.getChangeNum());
            if (auditStatus.equals("1")) {
                warehousingService.calculation(monthlyInventoryLog);
            }
            monthlyInventoryLog.setChangeNum(-monthlyInventoryLog.getChangeNum());

            monthlyInventoryLog.setLogId(orderId);
            monthlyInventoryLog.setAuditTime(DateUtils.getNowDate());
            monthlyInventoryLog.setAuditStatus(audit.getAuditStatus());
            monthlyInventoryLog.setUpdateBy(sysUser.getNickName());
            num = monthlyInventoryMapper.updateMonthlyInventoryLog(monthlyInventoryLog);

        } else if (orderType.equals("5")) {
            //采购退货
//            PurchaseReturnOrder purchaseReturnOrder = new PurchaseReturnOrder();
//            purchaseReturnOrder.setPurchaseReturnId(audit1.getOrderId());
//            purchaseReturnOrder.setAuditTime(DateUtils.getNowDate());
//            purchaseReturnOrder.setPurchaseReturnStatus(audit.getAuditStatus());
//            num = purchaseReturnMapper.updatePurchaseReturn(purchaseReturnOrder);

        } else if (orderType.equals("6")) {
            //销售退货
//            SaleReturnOrder saleReturnOrder = new SaleReturnOrder();
//            saleReturnOrder.setSaleReturnId(audit1.getOrderId());
//            saleReturnOrder.setAuditTime(DateUtils.getNowDate());
//            saleReturnOrder.setSaleReturnStatus(audit.getAuditStatus());
//            num = saleReturnMapper.updateSaleReturnOrder(saleReturnOrder);

        } else if (orderType.equals("7")) {
            //销售发票
            SalesInvoiceOrder salesInvoiceOrder = salesInvoiceMapper.selectSalesInvoiceOrderById(orderId);
            salesInvoiceOrder.setSalesInvoiceId(orderId);
            salesInvoiceOrder.setAuditTime(DateUtils.getNowDate());
            salesInvoiceOrder.setInvoiceStatus(audit.getAuditStatus());
            num = salesInvoiceMapper.updateSalesInvoiceOrder(salesInvoiceOrder);
            countIsInvoice(orderId);
        } else if (orderType.equals("8")) {
            MateProcurement mateProcurement = mateProcurementMapper.selectMateProcurementByOrderId(orderId);
            mateProcurement.setMateProcurementId(orderId);
            mateProcurement.setAuditTime(DateUtils.getNowDate());
            mateProcurement.setProcurementStatus(audit.getAuditStatus());
            if (auditStatus.equals("1")) {
                outboundMate(mateProcurement);
            }
            num = mateProcurementMapper.updateProcurement(mateProcurement);

        } else if (orderType.equals("9")) {
            MateOutbound mateOutbound = mateOutboundMapper.selectMateOutboundByOrderId(orderId);
            mateOutbound.setMateGoodsId(orderId);
            mateOutbound.setAuditTime(DateUtils.getNowDate());
            mateOutbound.setMateGoodsStatus(audit.getAuditStatus());
            if (auditStatus.equals("1")) {
                MateOutbound(mateOutbound);

            }
            num = mateOutboundMapper.updateMateOutbound(mateOutbound);

        }
        if (num != 0) {
            return auditMapper.updateAudit(audit);
        } else {
            return num;
        }
//        throw new RuntimeException("这是测试错误，自行修改。");
    }

    /**
     * 退回库存金额
     *
     * @param inventoryAmount 退回信息
     */
    private void returnInventorAmount(InventoryAmount inventoryAmount) {
        Long orderId = inventoryAmount.getOrderId();
        Long deptId = inventoryAmount.getDeptId();
        List<InventoryAmount> inventoryAmountList = new ArrayList<>();
        List<SaleGoodsModel> saleGoodsModels = saleGoodsMapper.selectSaleGoodsModelById(orderId);
        for (SaleGoodsModel saleGoodsModel : saleGoodsModels) {
            int num = saleGoodsModel.getNum();
            Long productId = saleGoodsModel.getProductId();
            String productType = saleGoodsModel.getProductType();
            String batch = saleGoodsModel.getBatch();
            InventoryAmount inventoryAmounts = new InventoryAmount();
            inventoryAmounts.setBatch(batch);
            inventoryAmounts.setProductType(productType);
            inventoryAmounts.setDeptId(deptId);
            inventoryAmounts.setProductId(productId);
            List<InventoryAmount> inventoryAmountsList = inventoryAmountMapper.selectInventorAmountLists(inventoryAmounts);
            if (inventoryAmountsList.size() != 0) {
                for (InventoryAmount amount : inventoryAmountsList) {
                    InventoryAmount inventoryAmount1 = new InventoryAmount();
                    inventoryAmount1.setUpdateTime(new Date());
                    inventoryAmount1 = amount;

                    int remainingNum = amount.getRemainingNum();
                    int executeNum = amount.getExecuteNum();
                    int i = executeNum - remainingNum;

                    if (num > i) {
                        amount.setRemainingNum(executeNum);
                        inventoryAmount1.setRemainingNum(executeNum);
                        num -= i;
                        inventoryAmountList.add(inventoryAmount1);
                    } else if (num <= i) {
                        amount.setRemainingNum(remainingNum + num);
                        inventoryAmount1.setRemainingNum(remainingNum + num);
                        num = 0;
                        inventoryAmountList.add(inventoryAmount1);
                        break;
                    }
                }

                inventoryAmountMapper.updateInventoryAmountList(inventoryAmountList);
            }
        }

    }

    /**
     * 计算销售发票信息，修改销货单的状态
     *
     * @param salesInvoiceId 条件
     * @return 结果
     */
    public int countIsInvoice(Long salesInvoiceId) {
        SalesInvoiceOrder salesInvoiceOrder = salesInvoiceMapper.selectSalesInvoiceOrderById(salesInvoiceId);
        List<SalesInvoiceModel> salesInvoiceModelList = salesInvoiceOrder.getSalesInvoiceModelList();
        List<Long> saleGoodsModelIdList = new ArrayList<>();
        if (salesInvoiceModelList.size() != 0) {
            for (SalesInvoiceModel salesInvoiceModel : salesInvoiceModelList) {
                Long saleGoodsModelId = salesInvoiceModel.getSaleGoodsModelId();
                saleGoodsModelIdList.add(saleGoodsModelId);
            }
        }
        List<SaleGoodsModel> saleGoodsModels = saleGoodsMapper.selectSaleGoodsModelByModelIdList(saleGoodsModelIdList);
        Map<Long, Long> map = new HashMap<>();
        List<Long> saleGoodsIdList = new ArrayList<>();

        if (saleGoodsModels.size() != 0) {
            for (SaleGoodsModel saleGoodsModel : saleGoodsModels) {
                Long saleGoodsId = saleGoodsModel.getSaleGoodsId();
                map.put(saleGoodsId, saleGoodsId);
                saleGoodsIdList.add(saleGoodsId);
            }
        }

        //获取新的list集合，去重
        List<Long> listNew = new ArrayList<Long>(new TreeSet<Long>(saleGoodsIdList));

//        //判断是否有销货单的开票信息不为0的销货单
//        List<Long> saleGoodsList = saleGoodsMapper.selectSaleGoodsIdByList(listNew);
//        //去除不为0的数据
//        List<Long> reduce1 = listNew.stream().filter(item -> !saleGoodsList.contains(item)).collect(toList());
//
////        listNew.removeAll(saleGoodsList);
//
//        if (reduce1.size() != 0) {
//            int i = saleGoodsMapper.updateSaleorderOrderIsPays(reduce1);
//        }
        if (listNew.size() != 0) {
            int i = saleGoodsMapper.updateSaleorderOrderIsPayes(listNew);
        }
        return 0;
    }

    /**
     * 用于统计数据计算库存
     *
     * @param procurementOrder 条件
     */
    @Transactional
    public void calculation(ProcurementOrder procurementOrder) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        //根据主键查询数据，判断是否含有产品规格型号子集
        if (procurementOrder.getProcurementModelList() != null) {
            //循环插入库存数据
            List<ProcurementModel> procurementModelList = procurementOrder.getProcurementModelList();
            WarehousingRecords warehousingRecords = new WarehousingRecords();
            for (ProcurementModel procurementModel : procurementModelList) {
                Long deptId = procurementModel.getDeptId();
                String productType = procurementModel.getProductType();
                Long productId = procurementModel.getProductId();
                String batch = procurementModel.getBatch();
                int warehousingAmount = procurementModel.getWarehousingAmount();
                Long allNuM = procurementModel.getAllNum();
                int purchaseNum = procurementModel.getPurchaseNum();
                String medicalNumber = procurementModel.getMedicalNumber();
                Date medicalEndTime = procurementModel.getMedicalEndTime();
                Date effectiveDate = procurementModel.getEffectiveDate();
                Date productionDate = procurementModel.getProductionDate();
                Long supplierId = procurementOrder.getSupplierId();
                //创建新的存储对象，存入库存
                Warehousing warehousing = new Warehousing();
                warehousing.setBatch(batch);
                warehousing.setSelectId(productId);
                warehousing.setDeptId(deptId);
                warehousing.setProductId(productId);
                warehousing.setProductType(productType);
                warehousing.setWarehousingNum(warehousingAmount);
                warehousing.setMedicalNumber(medicalNumber);
                warehousing.setEffectiveDate(effectiveDate);
                warehousing.setMedicalEndTime(medicalEndTime);
                warehousing.setProductionDate(productionDate);
                warehousing.setAmount(allNuM);
                Warehousing warehousing1 = warehousingMapper.selectWarehousing(warehousing);
                //存储本次操作的数量
                warehousingRecords.setInventoryNum(warehousingAmount);
                warehousingRecords.setAllnum(allNuM.intValue());
                //判断是否拥有该公司该产品该型号名称的库存记录
                if (warehousing1 == null) {
                    warehousingMapper.insertWarehousing(warehousing);
                } else {

                    int warehousingNum = warehousing1.getWarehousingNum();
                    Long amount = warehousing1.getAmount();

                    allNuM += amount;

                    if (allNuM < 0) {
                        throw new RuntimeException(batch + "批次库存不足，入库订单不能退回审核！");
                    }
                    // warehousing.setWarehousingNum(warehousingAmount);
                    warehousing.setAmount(allNuM);
                    warehousing.setWarehousingId(warehousing1.getWarehousingId());
                    warehousing.setUpdateBy(sysUser.getNickName());
                    warehousingMapper.updateWarehousing(warehousing);
                }
                Long warehousingId = warehousing.getWarehousingId();
                warehousingRecords.setWarehousingId(warehousingId);
                warehousingRecords.setSupplierId(supplierId);
                warehousingRecords.setInventoryStatus("0");
                warehousingRecords.setCreateBy(sysUser.getNickName());
                //   warehousingRecordsMapper.insertWarehousingRecords(warehousingRecords);
                warehousingRecordsMapper.deleteWarehousingRecords(procurementOrder.getProcurementWarehousingName());
            }
        }
    }

    /**
     * 出库审核退回
     *
     * @param saleGoodsOrder 退回详情
     */
    @Transactional
    public void outboundAudit(SaleGoodsOrder saleGoodsOrder) {
        //根据主键查询数据，判断是否含有产品规格型号子集
        HashMap hashMap = new HashMap();
        hashMap.put("saleGoodsId", saleGoodsOrder.getSaleGoodsId());
        SaleGoodsOrder saleGoodsOrder1 = saleGoodsMapper.selectSaleGoodsById(hashMap);
        if (!"2".equals(saleGoodsOrder.getSaleGoodsStatus())) {
            if (saleGoodsOrder1.getSaleGoodsModels() != null) {
                //循环插入库存数据
                List<SaleGoodsModel> saleGoodsModels = saleGoodsOrder1.getSaleGoodsModels();
                WarehousingRecords warehousingRecords = new WarehousingRecords();
                for (SaleGoodsModel saleGoodsModel : saleGoodsModels) {
                    int num = saleGoodsModel.getAllNum();
                    //找库存表 获取id
                    Warehousing warehousing = new Warehousing();
                    warehousing.setSelectId(saleGoodsModel.getProductId());
                    warehousing.setDeptId(saleGoodsOrder1.getDeptId());
                    warehousing.setProductId(saleGoodsModel.getProductId());
                    warehousing.setProductType(saleGoodsModel.getProductType());
                    warehousing.setBatch(saleGoodsModel.getBatch());
                    Warehousing warehousing1 = warehousingMapper.selectWarehousing(warehousing);
                    //存储本次减少的数量
                    warehousingRecords.setInventoryNum(-saleGoodsModel.getNum());
                    warehousingRecords.setAllnum(saleGoodsModel.getAllNum());
                    //判断是否拥有该公司该产品该型号名称的库存记录
                    if (warehousing1 != null) {
                        //int warehousingNum = warehousing1.getWarehousingNum();
                        Long warehousingNum = warehousing1.getAmount();
                        //int warehousingNum = warehousing1.getWarehousingNum();

                        Long num1 = num + warehousingNum;
                        warehousing.setAmount(num1);
                        warehousing.setWarehousingId(warehousing1.getWarehousingId());
                        if (warehousing.getAmount() < 0) {
                            new AjaxResult(AjaxResult.Type.ERROR, "库存不足");
                            throw new RuntimeException("库存不足");
                        }
                        warehousingMapper.updateWarehousing(warehousing);
                    } else {
                        new AjaxResult(AjaxResult.Type.ERROR, "没有找到该型号的数据，请确定是否有该型号库存");
                        throw new RuntimeException("没有找到该型号的数据，请确定是否有该型号库存");
                    }

                  /*  Long warehousingId = warehousing.getWarehousingId();
                    warehousingRecords.setWarehousingId(warehousingId);
                    warehousingRecords.setSupplierId(saleGoodsOrder1.getCustomerId());

                    warehousingRecords.setInventoryStatus("1");
                    warehousingRecords.setCreateBy(WXShiroUtils.getLoginName());
                    warehousingRecordsMapper.insertWarehousingRecords(warehousingRecords);*/
                    warehousingRecordsMapper.deleteWarehousingRecords(saleGoodsOrder.getSaleGoodsNum());

                }
            }
        }
    }

    @Transactional
    public void outboundMate(MateProcurement mateProcurement) {
        MateProcurement mateProcurement1 = mateProcurementMapper.selectMateProcurementBy(mateProcurement);
        if (!"2".equals(mateProcurement.getProcurementStatus())) {
            if (mateProcurement1.getMateProcurementModels() != null) {
                List<MateProcurementModel> mateProcurementModels = mateProcurement1.getMateProcurementModels();
                for (MateProcurementModel mateProcurementModel : mateProcurementModels) {
                    int num = Math.toIntExact(mateProcurementModel.getRealityNum());
                    MateWarehousing warehousing = new MateWarehousing();
                    warehousing.setMateproductId(mateProcurementModel.getMateproductId());
                    warehousing.setDeptId(mateProcurementModel.getDeptId());
                    warehousing.setEnterNum(mateProcurementModel.getEnterNum());
                    warehousing.setMateProductType(mateProcurementModel.getMateProductType());
                    MateWarehousing warehousing1 = mateWarehousingMapper.selectMateWarehousing(warehousing);
                    if (warehousing1 != null) {
                        int warehousingNum = warehousing1.getWarehousingNum();
                        int num1 = warehousingNum - num;
                        warehousing.setWarehousingNum(num1);
                        warehousing.setWarehousingId(warehousing1.getWarehousingId());
                        if (warehousing.getWarehousingNum() < 0) {
                            new AjaxResult(AjaxResult.Type.ERROR, "库存不足");
                            throw new RuntimeException("库存不足");
                        }
                        mateWarehousingMapper.updateMateWarehousing(warehousing);
                    } else {
                        new AjaxResult(AjaxResult.Type.ERROR, "没有找到该型号的数据，请确定是否有该型号库存");
                        throw new RuntimeException("没有找到该型号的数据，请确定是否有该型号库存");
                    }
                }
                warehousingRecordsMapper.deleteWarehousingRecords(mateProcurement.getMateOrdernum());

            }

        }
    }

    @Transactional
    public void MateOutbound(MateOutbound mateOutbound) {
        MateOutbound mateOutbound1 = mateOutboundMapper.selectMateOutboundBy(mateOutbound);
        if (!"2".equals(mateOutbound.getMateGoodsStatus())) {
            if (mateOutbound1.getMateOutboundModels() != null) {
                List<MateOutboundModel> mateOutbounds = mateOutbound1.getMateOutboundModels();
                for (MateOutboundModel mateOutboundModel : mateOutbounds) {
                    int num = mateOutboundModel.getNum();
                    MateWarehousing warehousing = new MateWarehousing();
                    warehousing.setMateproductId(mateOutboundModel.getMateproductId());
                    warehousing.setDeptId(mateOutboundModel.getDeptId());
                    warehousing.setMateBatch(mateOutboundModel.getMateBatch());
                    warehousing.setMateProductType(mateOutboundModel.getMateProductType());
                    MateWarehousing warehousing1 = mateWarehousingMapper.selectMateWarehousing(warehousing);
                    if (warehousing1 != null) {
                        int warehousingNum = warehousing1.getWarehousingNum();
                        int num1 = warehousingNum + num;
                        warehousing.setWarehousingNum(num1);
                        warehousing.setWarehousingId(warehousing1.getWarehousingId());
                        if (warehousing.getWarehousingNum() < 0) {
                            new AjaxResult(AjaxResult.Type.ERROR, "库存不足");
                            throw new RuntimeException("库存不足");
                        }
                        mateWarehousingMapper.updateMateWarehousing(warehousing);

                    } else {
                        new AjaxResult(AjaxResult.Type.ERROR, "没有找到该型号的数据，请确定是否有该型号库存");
                        throw new RuntimeException("没有找到该型号的数据，请确定是否有该型号库存");
                    }

                }
                warehousingRecordsMapper.deleteWarehousingRecords(mateOutbound.getMateGoodsNum());
            }


        }

    }

    /**
     * 查询订单审核列表
     *
     * @param audit 订单审核
     * @return 订单审核
     */
    @Override
    public List<Audit> selectAuditLists(Audit audit) {
        return auditMapper.selectAuditListes(audit);
    }

    /**
     * 插入金额明细表
     *
     * @param amountDetailed 需要插入的数据
     */
    @Override
    public void insertAmountDetailed(AmountDetailed amountDetailed) {
        Long orderId = amountDetailed.getOrderId();
        String orderType = amountDetailed.getOrderType();
        if (orderType.equals("0")) {
            ProcurementOrder procurementOrder = procurementOrderMapper.selectProcurementById(orderId);
            //订单金额
            BigDecimal purchaseAmount = procurementOrder.getPurchaseAmount();
            //订单金额(含税)
            BigDecimal taxAmount = procurementOrder.getTaxAmount();
            BigDecimal bigDecimal = new BigDecimal(0);

            amountDetailed.setCreateBy(WXShiroUtils.getSysUser().getUserName());
            amountDetailed.setTaxAmount(bigDecimal.add(purchaseAmount));
            amountDetailed.setTaxTotal(bigDecimal.add(taxAmount));
        } else {
            HashMap<String, Object> map = new HashMap<>();
            map.put("saleGoodsId", orderId);
            SaleGoodsOrder saleGoodsOrder = saleGoodsMapper.selectSaleGoodsById(map);
            BigDecimal saleGoodsTaxamount = saleGoodsOrder.getSaleGoodsTaxamount();
            BigDecimal saleGoodsAmount = saleGoodsOrder.getSaleGoodsAmount();
            BigDecimal bigDecimal = new BigDecimal(0);

            amountDetailed.setCreateBy(WXShiroUtils.getSysUser().getUserName());
            amountDetailed.setTaxAmount(bigDecimal.subtract(saleGoodsAmount));
            amountDetailed.setTaxTotal(bigDecimal.subtract(saleGoodsTaxamount));
        }
        amountDetailedMapper.insertAmountDetailed(amountDetailed);
    }

    @Override
    public AmountDetailed selectAmountDetailed(Long companyId) {
        return amountDetailedMapper.selectAmountDetailed(companyId);
    }

    @Override
    public void insertInventoryAmount(InventoryAmount inventoryAmount) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        String orderType = inventoryAmount.getOrderType();
        Long deptId = sysUser.getCompanyId();
        Long orderId = inventoryAmount.getOrderId();
        List<ProcurementModel> procurementModels = procurementOrderMapper.selectProcurementModelById(orderId);

        List<InventoryAmount> inventoryAmountList = new ArrayList<>();

        for (ProcurementModel procurementModel : procurementModels) {
            InventoryAmount inventoryAmounts = new InventoryAmount();
            inventoryAmounts.setDeptId(deptId);
            inventoryAmounts.setOrderId(orderId);
            inventoryAmounts.setOrderType("0");
            inventoryAmounts.setAuditId(inventoryAmount.getAuditId());
            inventoryAmounts.setProcurementWarehousingNo(procurementModel.getProcurementWarehousingNo());
            inventoryAmounts.setProductId(procurementModel.getProductId());
            inventoryAmounts.setProductType(procurementModel.getProductType());
            inventoryAmounts.setBatch(procurementModel.getBatch());
            inventoryAmounts.setTaxRate(procurementModel.getTaxRate());
            inventoryAmounts.setPrice(procurementModel.getPurchasePrice());
            inventoryAmounts.setTaxPrice(procurementModel.getTaxPrice());
            inventoryAmounts.setRemainingNum(procurementModel.getPurchaseNum());
            inventoryAmounts.setExecuteNum(procurementModel.getPurchaseNum());
            inventoryAmounts.setCreateBy(sysUser.getNickName());
            inventoryAmountList.add(inventoryAmounts);
        }
        inventoryAmountMapper.insertInventoryAmount(inventoryAmountList);
    }

    @Override
    public void updateInventoryAmount(InventoryAmount inventoryAmount) {

        Long orderId = inventoryAmount.getOrderId();
        Long companyId = SecurityUtils.getLoginUser().getUser().getCompanyId();

        List<InventoryAmount> inventoryAmountList = new ArrayList<>();
        List<SaleGoodsModel> saleGoodsModels = saleGoodsMapper.selectSaleGoodsModelById(orderId);
        for (SaleGoodsModel saleGoodsModel : saleGoodsModels) {
            String batch = saleGoodsModel.getBatch();
            Long productId = saleGoodsModel.getProductId();
            String productType = saleGoodsModel.getProductType();
            int num = saleGoodsModel.getNum();
            InventoryAmount inventoryAmounts = new InventoryAmount();
            inventoryAmounts.setDeptId(companyId);
            inventoryAmounts.setProductId(productId);
            inventoryAmounts.setProductType(productType);
            inventoryAmounts.setBatch(batch);
            List<InventoryAmount> inventoryAmountsList = inventoryAmountMapper.selectInventorAmountList(inventoryAmounts);
            if (inventoryAmountsList.size() != 0) {
                for (InventoryAmount amount : inventoryAmountsList) {

                    InventoryAmount inventoryAmount1 = new InventoryAmount();
                    inventoryAmount1.setUpdateTime(new Date());
                    inventoryAmount1 = amount;

                    int remainingNum = amount.getRemainingNum();
                    if (num > remainingNum) {
                        amount.setRemainingNum(0);
                        num -= remainingNum;
                        inventoryAmount1.setRemainingNum(0);
                        inventoryAmountList.add(inventoryAmount1);
                    } else if (num <= remainingNum) {
                        amount.setRemainingNum(remainingNum - num);
                        inventoryAmount1.setRemainingNum(remainingNum - num);
                        num = 0;
                        inventoryAmountList.add(inventoryAmount1);
                        break;
                    }
                }
            }
        }
        if (inventoryAmountList.size() != 0) {
            inventoryAmountMapper.updateInventoryAmountList(inventoryAmountList);
        }
    }

    /**
     * 查询库存总金额
     *
     * @param deptId 查询的公司主键
     * @return 结果
     */
    @Override
    public InventoryAmount selectInventorAmountCount(Long deptId) {
        return inventoryAmountMapper.selectInventorAmountCount(deptId);
    }
}